import React, { useCallback, useMemo, useState, useEffect } from "react"
import { Menu, Image } from "antd"
import { useNavigate, useLocation } from "react-router-dom"
import { connect } from "react-redux"

import "./Leftnav.less"
import logo from "../assets/img/logo.png"
import router from "../router"
import Icons from "../utils/icons"
import { setTitle } from "../store/actions"

function Leftnav(props) {
  const navigate = useNavigate()
  const location = useLocation()
  const pathname = location.pathname
  const rootSubmenuKeys = useMemo(() => [], [])
  const [items, setItems] = useState([])
  const { setTitle } = props

  const getItem = useCallback(
    (items, parse) => {
      return items.map((item) => {
        let { label, icon, path, children } = item
        let key = parse ? `/${parse}/${path}` : "/" + path
        rootSubmenuKeys.push(key)
        // 权限管理
        // if (key.indexOf("mail") !== -1) return false
        // console.log(label, icon, path, children, key, pathname.slice(6))
        if (key === pathname.slice(6)) setTitle(label)
        return {
          label,
          key,
          children: children ? getItem(children, path) : children,
          icon: <Icons style={{ fontSize: "16px" }} type={"icon-" + icon} />,
        }
      })
    },
    [rootSubmenuKeys, pathname, setTitle]
  )
  const [openKeys, setOpenKeys] = useState(["/" + pathname.split("/")[2]])

  const selectedKeys = [pathname.slice(6)]
  const go = ({ domEvent, key }) => {
    const title = domEvent.target.innerText
    setTitle(title)
    navigate(`.${key}`)
  }
  const onOpenChange = (keys) => {
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1)
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys)
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : [])
    }
  }
  useEffect(() => {
    setItems(getItem(router[1].children.slice(1)))
  }, [getItem])
  return (
    <div className="leftnav">
      <div className="logo">
        <Image preview={false} src={logo} />
      </div>
      <Menu
        theme="dark"
        mode="inline"
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        items={items}
        onClick={go}
        onOpenChange={onOpenChange}
      />
    </div>
  )
}
export default connect(() => ({}), {
  setTitle,
})(Leftnav)
